﻿/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2018. All rights reserved.
 * Description:
 * Author: 辛爱国 x30005137
 * Create: 2020-07-28
 * Notes: 无
 */
#include <QString>
#include <QMutex>
#include <QTime>
#include <QFile>
#include <QDebug>
#include <QCoreApplication>
#include <QDir>
#include <direct.h>
#if defined(Q_OS_WIN)
#if     defined(IDEASHAREKEY)
static const char *LOG_FILE_NAME = "./log/IdeaShare Key.log";
#else
static const char *LOG_FILE_NAME = "./log/IdeaShare.log";
#endif
#else // linux mac
#if     defined(IDEASHAREKEY)
static constexpr char *LOG_FILE_NAME = "/tmp/IdeaShare Key.log";
#else
static constexpr char *LOG_FILE_NAME = "/tmp/IdeaShare.log";
#endif
#endif

static QFile logFile(LOG_FILE_NAME);

/* 自动释放文件句柄 */
static class logger_lambda_ {
public:
    logger_lambda_()
    {
       //解决目录创建不了的问题
        QDir dir;
        if (!dir.exists("./log")) {
            dir.mkdir("./log");
        }
        if (logFile.size() > 10 * 1024 * 1024) { // 日志大小 10 * 1024 * 1024 字节
            logFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
        } else {
            logFile.open(QIODevice::WriteOnly | QIODevice::Append);
        }
    }
    ~logger_lambda_()
    {
        logFile.close();
    }
} logger_autorelease_;

/* 日志输出回调函数 */
void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();
    QString log;
    switch (type) {
        case QtDebugMsg:
            log = QString("Debug: ");
            break;

        case QtWarningMsg:
            log = QString("Error: ");
            break;

        case QtCriticalMsg:
            log = QString("Critical Error: ");
            break;

        case QtFatalMsg:
            log = QString("Fatal Error: ");
            break;

        default:
            log = QString("Unknow Msg Type : ");
            mutex.unlock();
            return;
    };
    QString filePath1 = QString(context.file);
    int index = filePath1.lastIndexOf("\\");
    QString filePath = filePath1.mid(index + 1);
    log += QTime::currentTime().toString("hh:mm:ss.zzz, File: ") + filePath;
    log += QString(", Line: ") + QString::number(context.line) + QString(" : %1\n").arg(msg);
    
    logFile.write(log.toStdString().c_str());
    logFile.flush();

    mutex.unlock();
}
